package com.fansl.allround.daemon.quartz.listener;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author fansl
 * @Description: 默认全局JobListener
 * @date 2020/1/14 17:58
 */
@Slf4j
@Component
public class DefaultGlobalJobListener implements JobListener {
    @Override
    public String getName() {
        return getClass().getSimpleName();
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext jobExecutionContext) {
        if(log.isDebugEnabled()){
            JobKey jobKey = jobExecutionContext.getJobDetail().getKey();
            log.debug("[{}]定时任务即将执行,时间：{}",jobKey,DateUtil.format(new Date(System.currentTimeMillis()),"yyyy-MM-dd HH:mm:ss:SSS"));
        }
    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) {
        if(log.isDebugEnabled()) {
            log.debug("[{}]定时任务被否决,不再执行", jobExecutionContext.getJobDetail().getKey());
        }
    }

    @Override
    public void jobWasExecuted(JobExecutionContext jobExecutionContext, JobExecutionException jobException) {
        if(log.isDebugEnabled()) {
            log.info("[{}]定时任务执行于{}结束",
                    jobExecutionContext.getJobDetail().getKey(),
                    DateUtil.format(new Date(System.currentTimeMillis()), "yyyy-MM-dd HH:mm:ss:SSS"));
        }
        if (jobException != null) {
            log.error("[{}]定时任务执行中发生异常，参数：{}，异常信息：{}",
                    jobExecutionContext.getJobDetail().getKey(),jobExecutionContext.getJobDetail(),jobException);
            try {
                jobExecutionContext.getScheduler().pauseJob(jobExecutionContext.getJobDetail().getKey());
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
    }
}
